package com.qk.management.web.filter;

import cn.hutool.core.util.ObjectUtil;
import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * &#064;author：zzq
 * &#064;createTime：2025/10/11 10:58
 * &#064;description： 登录校验过滤器
 */
//@WebFilter("/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    private static final String LOGIN_PATH = "/login";
    private static final String TOKEN_HEADER_NAME = "token";

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //将请求对象和响应对象转换成HttpServletRequest和HttpServletResponse对象
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //获取请求路径
        String path = request.getRequestURI();
        log.info("-----------拦截到的请求路径：{}-------------", path);
        //判断是否是登录请求
        boolean isLoginReq = ObjectUtil.equals(LOGIN_PATH, path);
        if (isLoginReq) {
            chain.doFilter(request, response);
        }
        //不是登录请求,获取请求头中的token令牌
        String token = request.getHeader(TOKEN_HEADER_NAME);
        if (ObjectUtil.isEmpty(token)) {
            //没有token,返回未登录
            response.setStatus(401);
        }
        //JWTUTIL验证token
        try {
            Claims claims = JwtUtils.parseToken(token);
            //取出用户信息
            log.info("-----------用户名称：{}-------------", claims.get("name"));
            log.info("-----------用户id：{}-------------", claims.get("id"));
            //放行
            chain.doFilter(request, response);
        } catch (Exception e) {
            log.error("token验证失败",e);
            response.setStatus(401);
        }

    }
}
